package com.bite.order.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse
        response, BlockException e) throws Exception {
        response.setContentType("text/html; charset=utf-8");
        String msg = "Blocked by Sentinel (flow limiting)";
        int status = 429;
        PrintWriter out = response.getWriter();

        //限流异常
        if (e instanceof FlowException) {
            msg = "触发限流, 请联系服务⽅进⾏调整";
        } else if (e instanceof DegradeException) {
            //降级异常
            msg = "触发降级异常";
        } else if (e instanceof AuthorityException) {
            //授权异常
            msg = "没有权限访问, 请联系服务⽅进⾏调整";
            status = 401;
        }

        response.setStatus(status);
        out.print(msg);
        out.flush();
        out.close();
    }
}